import axios from 'axios';

const instance = axios.create({
    timeout: 10000,
    responseType: 'json'
});

function getToken() {
    return localStorage.getItem("token")
}
// 添加请求拦截器
instance.interceptors.request.use(
    (request: any) => {
        const isToken = request.headers['Authorization']
        if (!isToken && getToken()) {
            request.headers['Authorization'] = getToken()
        }

        return request;
    },
    error => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.response.use(
    response => {

        const errorCode = response?.data?.errorCode;
        switch (errorCode) {
            case '401':
                // 根据errorCode，对业务做异常处理(和后端约定)
                break;
            default:
                break;
        }

        return response;
    },
    error => {
        console.log(error)

        const response = error.response;
        // eslint-disable-next-line
        return Promise.reject(response || { message: error.message });
    }
);

export default instance;
